#include <pthread.h>
#include "seqiot.h"
#include "sqlite.h"
#include "watchdog.h"
#include "daemon.h"

int main(int argc, char *argv[]) {
    int timeout = 10;
    int counter = 0;
    sqlite3 *db = NULL;

    log_init();

    if (argc > 1) {
        db = sqlite_open(argv[1]);
    } else {
        char buf[255];
        if (get_conf_file(buf, sizeof(buf)) >= 0) {
            db = sqlite_open(buf);
        }
    }

    if (NULL == db) {
        return EXIT_FAILURE;
    }

    vector_t daemons = vector_initializer;
    read_stmt_daemons(db, &daemons);

    wd_open(NULL);
    wd_set_timeout(timeout);
    for (int i = 0; running; ++i) {
        wd_tick();
        if (i % timeout == 0) {
            log_info("tick=%d", counter);
            daemon_find_pid_by_proc(&daemons);
            daemon_find_pid_by_file(&daemons);
            for (int j = 0; j < vector_size(&daemons); ++j) {
                daemon_t *daemon = vector_get(&daemons, j);
                if (0 == daemon->chk_cycle || 0 == counter % daemon->chk_cycle) {
                    daemon_check(daemon);
                }
            }

            ++counter;
        } else {
            sqlite3_sleep(1000);
        }
    }
    wd_close(NULL);

    vector_foreach(&daemons, (vector_foreach_callback) daemon_free);
    vector_clear(&daemons);

    log_fini();

    return EXIT_SUCCESS;
}